import re
import os
import time
import sys
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import win32api
import win32con
from win32com import client as wc
import docx
from functools import reduce
from aip import AipOcr

#百度aip的配置
APP_ID = '15513763'
API_KEY = 'Guex1tfH7m24wZFAFRCH3yj7'
SECRET_KEY = 'FQ79GN1RXeYqaFI6Bslb75BmjL1xzDNB'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

#下载附件名列表
docname = []
#文件的版本号
version = []
#拿到最新的文件名
newpfile = []
#列表titlelist和contentlist最后写入到这个字典
content = {}
#拿到验证码,添加到列表
yzmlist = []
#
VK_CODE ={'enter':0x0D, 'down_arrow':0x28}
#新的doc文件
newdocfile = []



#NONE
def first():    
    #账号
    zh = brower.find_element_by_id("username")
    zh.send_keys("01383317")
    
    #密码RL003694795
    mm = brower.find_element_by_id("password")
    mm.send_keys("liuj1a!wei")
    print("""
              请输入验证码
              有8秒时间
    		  请不要点击登录按钮
    		  """)
    time.sleep(8)
    #print("自动点击登陆")
    brower.find_element_by_css_selector(".f18.logn_lt.logn_btn.lh46").click()
    return brower

#下载验证码图片
def downimgcode():
    #键盘键按下
    def keyDown(keyName):
        win32api.keybd_event(VK_CODE[keyName], 0, 0, 0)
    #键盘键抬起
    def keyUp(keyName):
        win32api.keybd_event(VK_CODE[keyName], 0, win32con.KEYEVENTF_KEYUP, 0)
    yzm = brower.find_element_by_id("imgcode")
    action = ActionChains(brower).move_to_element(yzm)
    time.sleep(1)
    action.context_click(yzm).perform()
    time.sleep(1)
    #按v
    win32api.keybd_event(86, 0, 0, 0)
    win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(1)
    #按enter
    keyDown("enter")
    keyUp("enter")

#发送验证码	
def sendverifycode():
    fasyzm = brower.find_element_by_id("verifyCode")
    fasyzm.send_keys(yzm)

#发送账号,密码
def senduserpass():
    #账号
    zh = brower.find_element_by_id("username")
    zh.clear()
    zh.send_keys("01383317")    
    #密码RL003694795
    mm = brower.find_element_by_id("password")
    mm.clear()
    mm.send_keys("liuj1a!wei")



#查找目录下最新的图片
def find_pic_file():
    '''查找目录下最新的文件'''
    file_lists = os.listdir(dir1)
    file_lists.sort(key=lambda fn: os.path.getmtime(dir1 + "\\" + fn)
        if not os.path.isdir(dir1 + "\\" + fn) else 0)
    print('最新的文件为： ' + file_lists[-1])
    file1 = os.path.join(dir1, file_lists[-1])
    print('完整路径：', file1)
    return newpfile.append(file_lists[-1])

#读取图片
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

#读取文件夹,返回验证码进入yzmlist
def dodir():
    newfile1 = newpfile.pop()    
    #验证码存放的路径,还需要拼接
    luj = dir1 + '\\' + newfile1
	
    image = get_file_content(luj)
    #调用通用文字识别
    shibyzm = client.basicAccurate(image)
	#读取字典里面的内容,最后把空格去掉
    yzm1 = ((shibyzm['words_result'][0])['words']).replace(' ', '')
    return yzmlist.append(yzm1)

#读取文件里的流水号,去掉前面4位和最后的空格
def ReadFile():
    with open(r'C:\Users\01383317\doxx\lsh.txt', 'r') as f:
        nr = f.readlines()
    l = []
    for i in range(len(nr)):
        i = (nr.pop())[4:11]
        l.append(i)
    return l

#打开页面
def OpenNewTab(l):
    #brower = browers
    #print("打开新标签")
    for haoma in l:
        js = " window.open('http://itsm-rpt.sf-express.com/balantflow/task/getTaskDetail.do?taskId=%s')" % (haoma)
        time.sleep(2)
        brower.execute_script(js)

#操作页面
def DoWork():
        tabs = brower.window_handles
        brower.switch_to_window(tabs[-1])
        time.sleep(2)
        a = brower.find_elements_by_class_name("divTitle")
        b = brower.find_elements_by_class_name("divControl")
        dictname = b[0].text
        time.sleep(3)

        #获取到的版本号
        getV = []
        #获取key value
        titlelist = []
        contentlist = []
        for i1 in range(len(a)):
            if a[i1].text == '系统版本号：':
                print("系统编码:", b[0].text, "系统版本号:", b[i1].text)               
                getV.append(b[i1].text)

        for aa in range(len(a)):
            titlelist.append(a[aa].text)
            contentlist.append(b[aa].text)

        try:
            fuj = brower.find_element_by_xpath('//*[@id="divStepContent2078"]/table/tbody/tr/td[2]/ul/li[2]/a')
            fuj.click()
            time.sleep(1)
        except:
            fuj = brower.find_element_by_xpath('//*[@id="divStepContent3678"]/table/tbody/tr/td[2]/ul/li[2]/a')
            fuj.click()
            time.sleep(1)

        try:#先匹配docx,不然会匹配出错.
            wjm = brower.find_element_by_id("divFileGroup11").text
            wjm1 = re.match( r'(.*\.docx\b)', wjm, re.M|re.I)
            wjm2 = wjm1.group(1)
            print(wjm2)
            brower.find_element_by_link_text(wjm2).click()
        except:
            wjm = brower.find_element_by_id("divFileGroup11").text
            wjm1 = re.match( r'(.*\.doc\b)', wjm, re.M|re.I)
            wjm2 = wjm1.group(1)
            print(wjm2)
            brower.find_element_by_link_text(wjm2).click()
        content[dictname] = dict(zip(titlelist, contentlist))
        find_doc_file()
        brower.close()
        return docname.append(wjm2), version.append(str(getV[0]))#, content[dictname]

#最新的doc/docx文件
def find_doc_file(dir1):
    '''查找目录下最新的文件'''
    file_lists = os.listdir(dir1)
    file_lists.sort(key=lambda fn: os.path.getmtime(dir1 + "\\" + fn)
        if not os.path.isdir(dir1 + "\\" + fn) else 0)
    print('最新的文件为： ' + file_lists[-1])
    file1 = os.path.join(dir1, file_lists[-1])
    print('完整路径：', file1)
    return newdocfile.append(file_lists[-1])

#转换doc	
def ZhuanHuanDoc():
    wjm2 = docname.pop()#从列表拿最后一个文件的文件名,并从列表出删去
    banbh = version.pop()#从列表拿最后一个文件的版本号,并从列表出删去
#
    houzm = wjm2.split('.')[-1]#拿后缀名
    #wjm3 = wjm2.split('.')#
    #mingz1 = wjm3.pop() #去掉文件名的后缀
    #fileName=reduce(lambda x, y:str(x)+str(y),wjm3)#合并列表里面的文字
    w = []
    e = ['d','o','c','x']
    for i in wjm2:
        w.append(i)
        c1 = reduce(lambda x, y:str(x) + str(y),w[-3:])
        if c1 == "doc":
	        del(w[-3:])
	        w.extend(e)		
    name2 = reduce(lambda x, y:str(x)+str(y),w)#添加docx之后的文件名
    
    #拼接文件路径和地址名
    dress1 = r"D:\user\Downloads"
    dress2 = r"D:\user\Downloads" + "\\" + wjm2#初始下载地址的路径+文件名
    #转换之后的文件名
    name3 = r"D:\user\Downloads" + "\\" + name2
    
    def get_docx(file_name):
        d = docx.opendocx(file_name)
        doc = docx.getdocumenttext(d)
        return doc
	
    if houzm == "doc":
        word = wc.Dispatch("Word.Application")
        doc = word.Documents.Open(dress2)#打开文件
        doc.SaveAs(name3, 12)#保存为docx
        doc.Close()
        word.Quit()
        doc = get_docx(name3)
        #print(doc)  # 
        if banbh in doc:
            print("文件名:%s 版本号:%s  在文档内" % (name2, banbh))
        else:
            print('NO IN DOCX,PLEASE CHECK')
            #pass
    elif houzm == "docx":
        doc = get_docx(dress2)
        #print(doc)  #
        if banbh in doc:
            print("文件名:%s 版本号:%s  在文档内" % (wjm2, banbh))
        else:
            print('NO IN DOCX,PLEASE CHECK')


#图片的路径分片,返回完整的路径'D:\\user\\Downloads\\imgcode (7).jpg'
def codesplit(file1):
    a = file1.split('\\')[-1]
    pdress = dir1 + '\\' + a
    return pdress




if __name__ == "__main__":
    brower = webdriver.Chrome(executable_path = r"D:/user/Downloads/chromedriver")
    brower.get("http://itsm-rpt.sf-express.com/balantflow/")
    dir1 = r'D:\user\Downloads'
	
    downimgcode()
    #读取下载目录的文件夹,识别最新的文件
    find_pic_file()
    #find_doc_file	
    dodir()
    yzm = yzmlist.pop()
    print(yzm)
    print(docname, '\n', version, '\n', content, '\n', len(content))
    
    while 1:
        downimgcode()
        find_pic_file()
        dodir()
        yzm = yzmlist.pop()

        if len(yzm) < 4:
            brower.refresh()
        
            downimgcode()
            #读取下载目录的文件夹,识别最新的文件
            find_pic_file()    	
            dodir()
            yzm = yzmlist.pop()
            print('len(yzm) < 4 :', yzm)
            
        if len(yzm) == 4:
            senduserpass()
            print('len(yzm) == 4 :', yzm)
            senduserpass()
            sendverifycode()
            time.sleep(1)
            brower.find_element_by_css_selector(".f18.logn_lt.logn_btn.lh46").click()
    
    OpenNewTab(ReadFile())#按照流水号打开页面
    time.sleep(1)	
	



    for i in range(len(ReadFile())):
        DoWork()

    time.sleep(1)
    print(docname, '\n', version, '\n', content, '\n', len(content))
		
    for j in range(len(docname)):
        print(docname, '\n', version)
        ZhuanHuanDoc()

        










